package com.hinnotek.amoeba.ui.activity.old

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.adapters.old.ImageSelectGridAdapter
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.*
import com.hinnotek.amoeba.databinding.ActivityWipeOutAddBinding
import com.hinnotek.amoeba.databinding.IncludeWoWipeOutAddLayoutBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.utilities.*
import com.hinnotek.amoeba.viewmodels.AmibaReimburseViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.lee.common.utils.SharedPreUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint
import java.io.File
import java.io.FileNotFoundException
import java.util.*

@Suppress("NAME_SHADOWING")
@AndroidEntryPoint
class WipeOutModifyActivity : BaseActivity<ActivityWipeOutAddBinding>(),
    ImageSelectGridAdapter.OnAddPicClickListener {

    private var mAdapter: ImageSelectGridAdapter? = null
    private var mSelectList: MutableList<LocalMedia> = ArrayList<LocalMedia>()
    private var orgId = 0
    private var customerId = 0
    private var amibaCustomerProjectId = 0
    private var amibaProjectId = 0
    private var orgName: String = ""
    private lateinit var amibaReimburseByIdBean: AmibaReimburseByIdBean
    private var productTypePictures: List<AmibaReimbursePictures>? = null

    val viewMedel by viewModels<AmibaReimburseViewModel>()
    val publicViewMedel by viewModels<PublicInterfaceViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("添加报销申请")
        setContentView(R.layout.activity_wipe_out_add)
    }

    override fun initVew() {

        bindingView.rbWoP.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                bindingView.llChooseUnit.visibility = View.GONE
                bindingView.llWoChooseProject.visibility = View.GONE
                bindingView.llWoChoosePdProject.visibility = View.VISIBLE
            } else {
                bindingView.llChooseUnit.visibility = View.VISIBLE
                bindingView.llWoChooseProject.visibility = View.VISIBLE
                bindingView.llWoChoosePdProject.visibility = View.GONE
            }
        }


        bindingView.tvWoHappenDate.setOnClickListener { v: View ->
            IntentUtils.startActivityForResult(
                this,
                MaterialDesignCalendarActivity::class.java,
                null,
                111
            )
        }

        bindingView.rbWoDetails.setOnClickListener { v ->
            val productBinding = DataBindingUtil.inflate<IncludeWoWipeOutAddLayoutBinding>(
                layoutInflater,
                R.layout.include_wo_wipe_out_add_layout,
                bindingView.llWoDetails,
                false
            )
            bindingView.llWoDetails.addView(productBinding.root)

            productBinding.tvWoHappenDate.setOnClickListener {
                IntentUtils.startActivityForResult(
                    this@WipeOutModifyActivity,
                    MaterialDesignCalendarActivity::class.java,
                    null,
                    222
                )
            }
            productBinding.tvDel
                .setOnClickListener { v1: View? -> bindingView.llWoDetails.removeView(productBinding.root) }
        }
        bindingView.superButtonSubmit.setOnClickListener(View.OnClickListener { v: View? ->
            if (ClickUtil.isFastClick()) {
                return@OnClickListener
            }
            val amibaReimburseProjectJson = mutableListOf<AmibaReimburseProjectJson>()
            var provideProjectName = ""
            var customerName = ""
            var projectName = ""

            if (bindingView.rbWoP.isChecked) {
                provideProjectName =
                    bindingView.escWoChoosePdProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(provideProjectName)) {
                    ToastUtils.show(mContext, "请选择选择项目")
                    return@OnClickListener
                }
            } else {
                customerName = bindingView.escWoChooseUnit.editText.text.toString().trim()
                if (StringUtils.isEmpty(customerName)) {
                    ToastUtils.show(mContext, "请选择签署单位")
                    return@OnClickListener
                }
                projectName = bindingView.escWoChooseProject.editText.text.toString().trim()
                if (StringUtils.isEmpty(projectName)) {
                    ToastUtils.show(mContext, "请选择选择项目")
                    return@OnClickListener
                }
            }
            val reimburseDate = bindingView.tvWoHappenDate.text.toString().trim()

            val metWoContentS = bindingView.metWoContent.getContentText().trim()
            if (StringUtils.isEmpty(metWoContentS)) {
                ToastUtils.show(mContext, "请填写报销内容")
                return@OnClickListener
            }
            val reimburseNum = bindingView.etWoNumberOfDocuments.text.toString().trim()

            val reimburseMoney = bindingView.etWoMoney.getText().toString().trim()
            if (StringUtils.isEmpty(reimburseMoney)) {
                ToastUtils.show(mContext, "请填写报销金额")
                return@OnClickListener
            }
            val reimburseDetail =
                bindingView.metWoChargeDetails.contentText.trim()
            amibaReimburseProjectJson.add(
                AmibaReimburseProjectJson(
                    reimburseDate,
                    metWoContentS,
                    reimburseNum,
                    reimburseMoney,
                    reimburseDetail
                )
            )
            for (i in 0 until bindingView.llWoDetails.childCount) {
                val tvWoHappenDateSV = bindingView.tvWoHappenDate.text.toString().trim()
                val metWoContentSV = bindingView.metWoContent.contentText.trim()
                if (StringUtils.isEmpty(metWoContentSV)) {
                    ToastUtils.show(mContext, "请填写报销内容")
                    return@OnClickListener
                }
                val etWoNumberOfDocumentsSV = bindingView.etWoNumberOfDocuments.text.toString().trim()
                val etWoMoneySV = bindingView.etWoMoney.text.toString().trim()
                if (StringUtils.isEmpty(etWoMoneySV)) {
                    ToastUtils.show(mContext, "请填写报销金额")
                    return@OnClickListener
                }
                val reimburseDetail = bindingView.metWoChargeDetails.contentText.trim()
                amibaReimburseProjectJson.add(
                    AmibaReimburseProjectJson(
                        tvWoHappenDateSV,
                        metWoContentSV,
                        etWoNumberOfDocumentsSV,
                        etWoMoneySV,
                        reimburseDetail
                    )
                )
            }
            val reimburseprojectjsonS = Gson().toJson(amibaReimburseProjectJson)
            val escWoRelatedApproverS = bindingView.escWoRelatedApprover.editText.text.toString().trim()
            if (StringUtils.isEmpty(escWoRelatedApproverS)) {
                ToastUtils.show(mContext, "请选择关联审批人")
                return@OnClickListener
            }
            val files1: MutableList<File> = ArrayList()
            for (i in mSelectList.indices) {
                if (!mSelectList[i].getPath().startsWith("http")) {
                    files1.add(File(mSelectList[i].getPath()))
                }
            }
            val idList: MutableList<Int> = ArrayList()
            for (i in productTypePictures!!.indices) {
                val path = productTypePictures!![i].pictureUrl
                var id = -1
                for (i1 in mSelectList.indices) {
                    if (path == mSelectList[i1].getPath()) {
                        id = i1
                    }
                }
                if (id == -1) {
                    idList.add(productTypePictures!![i].amibaReimbursePictureId)
                }
            }
            var deleteIds = ""
            val stringBuffer = StringBuffer()
            for (i in idList.indices) {
                stringBuffer.append(idList[i].toString() + ",")
            }
            deleteIds = stringBuffer.toString()

            updateAmibaReimburse(
                amibaReimburseByIdBean.amibaReimburseId,
                orgId,
                orgName,
                customerId,
                customerName,
                amibaCustomerProjectId,
                projectName,
                amibaProjectId,
                provideProjectName,
                files1.toTypedArray(),
                deleteIds,
                reimburseprojectjsonS
            )
        })
        setData()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                111 -> bindingView.tvWoHappenDate.text = data?.getStringExtra("date")
                222 -> bindingView.tvWoHappenDate.text = data?.getStringExtra("date")
                PictureConfig.CHOOSE_REQUEST -> {
                    // 图片选择
                    mSelectList = PictureSelector.obtainMultipleResult(data)
                    mAdapter?.setSelectList(mSelectList)
                    mAdapter?.notifyDataSetChanged()
                }
            }
        }
    }

    override fun setData() {
        orgId = SharedPreUtils.getInteger("orgId", 0)
        orgName = SharedPreUtils.getString("orgName")
        amibaReimburseByIdBean = intent.getSerializableExtra("detail") as AmibaReimburseByIdBean
        if (amibaReimburseByIdBean.amibaReimburseType == 1) {
            bindingView.rbWoP.isChecked = true
        } else {
            bindingView.rbWoPj.isChecked = true
        }
        if (amibaReimburseByIdBean.amibaReimburseType == 1) {
            bindingView.escWoChoosePdProject.setText(amibaReimburseByIdBean.provideProjectName)
        } else {
            bindingView.escWoChooseUnit.setText(amibaReimburseByIdBean.customerName)
            bindingView.escWoChooseProject.setText(amibaReimburseByIdBean.projectName)
        }
        for (i in amibaReimburseByIdBean.amibaReimburseProjects.indices) {
            val amibaReimburseProjects: AmibaReimburseProjects =
                amibaReimburseByIdBean.amibaReimburseProjects.get(i)
            if (i == 0) {
                bindingView.tvWoHappenDate.text = amibaReimburseProjects.reimburseDate
                bindingView.metWoContent.contentText = amibaReimburseProjects.reimburseContent
                bindingView.etWoNumberOfDocuments.setText(amibaReimburseProjects.reimburseNum)
                bindingView.etWoMoney.setText(amibaReimburseProjects.reimburseMoney)
                bindingView.metWoChargeDetails.contentText = amibaReimburseProjects.reimburseDetail
            } else {
                val addViewProjects = DataBindingUtil.inflate<IncludeWoWipeOutAddLayoutBinding>(
                    layoutInflater,
                    R.layout.include_wo_wipe_out_add_layout,
                    bindingView.llWoDetails,
                    false
                )
                bindingView.llWoDetails.addView(addViewProjects.root)
                addViewProjects.tvWoHappenDate.text = amibaReimburseProjects.reimburseDate
                addViewProjects.metWoContent.contentText = amibaReimburseProjects.reimburseContent
                addViewProjects.etWoNumberOfDocuments.setText(amibaReimburseProjects.reimburseNum)
                addViewProjects.etWoMoney.setText(amibaReimburseProjects.reimburseMoney)
                addViewProjects.metWoChargeDetails.contentText =
                    amibaReimburseProjects.reimburseDetail
                addViewProjects.tvWoHappenDate.setOnClickListener {
                    IntentUtils.startActivityForResult(
                        this@WipeOutModifyActivity,
                        MaterialDesignCalendarActivity::class.java,
                        null,
                        222
                    )
                }
                addViewProjects.tvDel
                    .setOnClickListener { v1: View? ->
                        bindingView.llWoDetails.removeView(
                            addViewProjects.root
                        )
                    }
            }
        }
        productTypePictures = amibaReimburseByIdBean.amibaReimbursePictures
        val manager = GridLayoutManager(mContext, 3, RecyclerView.VERTICAL, false)

        bindingView.rlvWoEvidence.layoutManager = manager
        bindingView.rlvWoEvidence.adapter =
            ImageSelectGridAdapter(mContext, this).also { mAdapter = it }
        for (data in amibaReimburseByIdBean.amibaReimbursePictures) {
            val localMedia = LocalMedia()
            localMedia.path = data.pictureUrl
            localMedia.compressPath = data.pictureUrl
            mSelectList.add(localMedia)
        }
        mAdapter?.setSelectList(mSelectList)
        mAdapter?.setSelectMax(9)
        mAdapter?.setOnItemClickListener(object : ImageSelectGridAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, v: View?) {
                PictureSelector.create(this@WipeOutModifyActivity)
                    .themeStyle(R.style.XUIPictureStyle).openExternalPreview(position, mSelectList)
            }
        })
        bindingView.escWoRelatedApprover.setText(amibaReimburseByIdBean.approvalUser)
        bindingView.escWoRelatedApprover.isEnabled = true
        bindingView.tvWoCc.text = amibaReimburseByIdBean.sendUser

        publicViewMedel.getAmibaProjectListByOrgId(orgId)
            .observe(this, object : ObserverState<MutableList<AmibaProjectListBean>>() {
                override fun onDataChange(data: MutableList<AmibaProjectListBean>) {
                    val stringArray = arrayOfNulls<String>(data.size).apply {
                        for (index in data.indices) {
                            this[index] = data[index].projectName
                        }
                    }
                    bindingView.escWoChoosePdProject.initAdapter(stringArray)
                    bindingView.escWoChoosePdProject.setOnItemClickListener { parent, view, position, id ->
                        amibaProjectId = data[position].amibaProjectId
                    }
                    super.onDataChange(data)
                }
            })

        publicViewMedel.getAmibaCustomerListByOrgId(orgId).observe(this,object : ObserverState<MutableList<AmeobaCustomerListBean>>() {
            override fun onDataChange(data: MutableList<AmeobaCustomerListBean>) {
                val stringArray = arrayOfNulls<String>(data.size).apply {
                    for (index in data.indices) {
                        this[index] = data[index].customerName
                    }
                }
                bindingView.escWoChoosePdProject.initAdapter(stringArray)
                bindingView.escWoChoosePdProject.setOnItemClickListener { parent, view, position, id ->
                    amibaCustomerProjectId = data[position].customerId
                }
                super.onDataChange(data)
            }
        })
    }

    override fun onAddPicClick() {
        Utils.getPictureSelector(this)
            .selectionMedia(mSelectList)
            .maxSelectNum(9)
            .forResult(PictureConfig.CHOOSE_REQUEST)
    }

    /**
     * 修改报销申请接口
     */
    private fun updateAmibaReimburse(
        amibaReimburseId: Int,
        orgId: Int,
        orgName: String,
        customerId: Int,
        customerName: String,
        amibaCustomerProjectId: Int,
        projectName: String,
        amibaProjectId: Int,
        provideProjectName: String,
        imgs: Array<File>,
        deleteIds: String,
        amibaReimburseProjectJson: String
    ) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val map = mutableMapOf<String, Any>().apply {
            put("amibaReimburseId", amibaReimburseId)
            put("amibaReimburseType", if (bindingView.rbWoP.isChecked()) 1 else 2)
            put("orgId", orgId)
            put("orgName", orgName)
            if (!bindingView.rbWoP.isChecked) {
                put("customerId", customerId)
                put("customerName", customerName)
                put("amibaCustomerProjectId", amibaCustomerProjectId)
                put("projectName", projectName)
            } else {
                put("amibaProjectId", amibaProjectId)
                put("provideProjectName", provideProjectName)
            }
            try {
                put("imgs", imgs)
                put("deleteIds", deleteIds)
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
            put("amibaReimburseProjectJson", amibaReimburseProjectJson)
        }
        viewMedel.updateAmibaReimburse(getRequestBody(map))
            .observe(this, object : ObserverState<BaseBean>() {
                override fun onDataChange(data: BaseBean) {
                    customDialog.dismiss()
                    finishActivity()
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog.dismiss()
                    ToastUtils.showShort(mContext, msg)
                    super.onError(msg, code)
                }
            })

    }
}